# encoding: utf-8
from django import template
from datetime import datetime
from django.utils.safestring import mark_safe
from django.utils.timezone import now as now_func, localtime

register = template.Library()

@register.filter(name='time_since')
def time_since(value):
    if isinstance(value, datetime):
        now = now_func()
        timestamp = (now - value).total_seconds()
        if timestamp < 60:
            return '刚刚'
        elif 60 <= timestamp < 60 * 60:
            minutes = int(timestamp / 60)
            return '%s分钟前' % minutes
        elif 60 * 60 <= timestamp < 60 * 60 * 12:
            hours = int(timestamp / (60 * 60))
            return '%s小时前' % hours
        elif 60 * 60 * 12 <= timestamp < 60 * 60 * 12 * 30:
            days = int(timestamp / (60 * 60 * 12))
            return '%s天前' % days
        elif 60 * 60 * 12 * 30 <= timestamp < 60 * 60 * 12 * 30 * 12:
            months = int(timestamp / (60 * 60 * 12 * 30))
            return '%s月前' % months
        elif timestamp >= 60 * 60 * 12 * 30 * 12:
            return value.strftime("%Y/%m/%d %H:%M")
    else:
        return value


@register.filter
def time_format(value):
    if not isinstance(value, datetime):
        return value
    return localtime(value).strftime("%Y/%m/%d %H:%M:%S")

def generate_comment_html(sub_comment_dic, margin_left):
    # html = '<ul class="sub-comment-list" style="margin-left: %spx;">' % margin_left
    html = '</ul>'
    # 遍历子评论字典
    for k, v in sub_comment_dic.items():
        # 子评论第一层
        # 如果下面还有子节点，递归继续添加
        if v:
            html = generate_comment_html(v, margin_left + 15) + html
        html = '<li class="sub-li"> \
                    <div class="comment-info"> \
                        <img src="https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=229504038,2135463436&fm=26&gp=0.jpg"alt="" class="avatar"> \
                        <span class="author"> ' + k.author.username + ' </span> \
                        <span style="float: left; margin-left: 20px;">@</span>\
                        <span class="author">' + k.reply_to.username + '</span> \
                        <span class="pub-time">' + time_since(k.pub_time) + ' </span> \
                    </div> \
                    <div class="comment-content">' + k.content + '</div> \
                    <div class="more-opt"><button data-reply-user-id="' + k.author.pk + '" data-id="' + str(k.pk) + '">回复</button></div>' + html
        html += '</li>'
    # html += '</ul>'
    html = '<ul class="sub-comment-list" style="margin-left: %spx;">' % margin_left + html
    return html

def tree_search(comment_dic, comment_obj):
    """
    递归查找父节点
    :param comment_dic:
    :param comment_obj:
    :return:
    """
    for k, v in comment_dic.items():
        # 如果这个字典的k等于comment_obj的parent, 那么comment_obj的父节点就找到了
        if k == comment_obj.parent:
            # 找到的话，把自己插入到父节点下面，同时留个口，以防自己下面还有子节点
            comment_dic[k][comment_obj] = {}
            # 找到，且插入完成，返回
            return
        else:
            # 没找到，往下一层递归查找
            tree_search(comment_dic[k], comment_obj)

@register.filter
def build_comment_tree(comment_list):
    # 评论树空字典
    comment_dic = {}
    # 循环遍历该comment_dic
    for comment_obj in comment_list:
        # 如果comment没有parent, 那么它错位根节点构造一个评论树中的一棵树
        if comment_obj.parent is None:
            comment_dic[comment_obj] = {}
        else:
            # 如果有parent，稍后递归查找它的父节点
            tree_search(comment_dic, comment_obj)
    # 循环过后，所有comment归位，评论树正确建立
    # 接下来构造一个具有层级关系的html，传给前台，让前台能够正确显示comment的层级关系
    # html = '<ul class="parent-comment-list">'
    html = "</ul>"
    # 思路就是从构件好的comment_dic字典中，从父节点开始递归拼接html字符串，最后一个子节点字典的value是空了，表示遍历完了
    margin_left = 0
    for k, v in comment_dic.items():
        html = '</li>' + html
        # 通过递归把k的儿子都加上
        html = generate_comment_html(v, margin_left + 15) + html
        # 第一层html
        html = '<li class="parent-li"> \
                    <div class="comment-info"> \
                        <img src="https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=229504038,2135463436&fm=26&gp=0.jpg" alt="" class="avatar"> \
                        <span class="author">' + k.author.username + '</span> \
                        <span class="pub-time">' + time_since(k.pub_time) + '</span> \
                    </div> \
                    <div class="comment-content">' + k.content + '</div> \
                    <div class="more-opt"><button data-reply-user-id="' + k.author.pk + '" data-id="' + str(k.pk) + '">回复</button></div>' + html
    # html += "</ul>"
    html = '<ul class="parent-comment-list">' + html
    return mark_safe(html)
